<template>
  <div class="classroom-resource-wrapper">
    <el-card>
      <div class="header-bar">
        <span class="title">教室资源与规则管理</span>
        <el-button type="primary" @click="openAddDialog">新增教室</el-button>
      </div>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="教室资源管理" name="resource">
          <div class="search-bar">
            <el-input v-model="searchForm.classroomCode" placeholder="教室编号" style="width: 160px; margin-right: 8px;" clearable />
            <el-select v-model="searchForm.classroomType" placeholder="教室类型" style="width: 140px; margin-right: 8px;" clearable>
              <el-option v-for="(label, value) in classroomTypeOptions" :key="value" :label="label" :value="value" />
            </el-select>
            <el-input v-model.number="searchForm.capacity" placeholder="容量≥" style="width: 120px; margin-right: 8px;" clearable />
            <el-select v-model="searchForm.status" placeholder="状态" style="width: 120px; margin-right: 8px;" clearable>
              <el-option v-for="(label, value) in statusOptions" :key="value" :label="label" :value="value" />
            </el-select>
            <el-button type="primary" @click="fetchData">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
          <el-table :data="tableData" style="width: 100%; margin-top: 16px;" v-loading="loading">
            <el-table-column prop="classroomCode" label="教室编号" width="120" />
            <el-table-column prop="campus" label="校区" width="100" />
            <el-table-column prop="building" label="楼宇" width="100" />
            <el-table-column prop="floor" label="楼层" width="80" />
            <el-table-column prop="capacity" label="容量" width="80" />
            <el-table-column prop="classroomType" label="教室类型" width="120">
              <template #default="{ row }">
                {{ classroomTypeOptions[row.classroomType] || row.classroomType }}
              </template>
            </el-table-column>
            <el-table-column prop="equipmentList" label="设备清单" min-width="160">
              <template #default="{ row }">
                <span v-if="Array.isArray(row.equipmentList)">{{ row.equipmentList.join('，') }}</span>
                <span v-else>{{ row.equipmentList }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="statusTagType(row.status)">{{ statusOptions[row.status] || row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(row)" plain>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-bar">
            <el-pagination
              background
              layout="prev, pager, next, jumper, ->, total"
              :total="total"
              :page-size="pageSize"
              :current-page="pageNum"
              @current-change="onPageChange"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="教室规则管理" name="rule">
          <div style="padding: 32px; color: #888;">（可选）此处可扩展教室规则管理功能</div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 新增/编辑教室弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogMode === 'add' ? '新增教室' : '编辑教室'" width="500px" @close="resetDialog">
      <el-form :model="dialogForm" :rules="dialogRules" ref="dialogFormRef" label-width="100px">
        <el-form-item label="教室编号" prop="classroomCode">
          <el-input v-model="dialogForm.classroomCode" :disabled="dialogMode==='edit'" />
        </el-form-item>
        <el-form-item label="校区" prop="campus">
          <el-input v-model="dialogForm.campus" />
        </el-form-item>
        <el-form-item label="楼宇" prop="building">
          <el-input v-model="dialogForm.building" />
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-input-number v-model="dialogForm.floor" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input-number v-model="dialogForm.capacity" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="教室类型" prop="classroomType">
          <el-select v-model="dialogForm.classroomType" style="width: 100%">
            <el-option v-for="(label, value) in classroomTypeOptions" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备清单" prop="equipmentList">
          <el-select v-model="dialogForm.equipmentList" multiple filterable allow-create default-first-option style="width: 100%">
            <el-option v-for="item in equipmentOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="dialogForm.status" style="width: 100%">
            <el-option v-for="(label, value) in statusOptions" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDialogSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import axios from 'axios'

// Tab切换
const activeTab = ref('resource')

// 搜索表单
const searchForm = reactive({
  classroomCode: '',
  classroomType: '',
  capacity: undefined,
  status: ''
})

// 分页与表格数据
const tableData = ref<any[]>([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 字典
const classroomTypeOptions: Record<string, string> = {
  NORMAL: '普通教室',
  LAB: '实验室',
  LECTURE: '阶梯教室',
  MULTIMEDIA: '多媒体教室',
  EXAM: '考场'
}
const statusOptions: Record<string, string> = {
  AVAILABLE: '可用',
  MAINTENANCE: '维护中',
  DISABLED: '停用'
}
const equipmentOptions = ['投影仪', '黑板', '电脑', '音响', '空调', '讲台']

// 弹窗相关
const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const dialogForm = reactive<any>({})
const dialogFormRef = ref<FormInstance>()
const dialogRules = {
  classroomCode: [ { required: true, message: '请输入教室编号', trigger: 'blur' } ],
  building: [ { required: true, message: '请输入楼宇', trigger: 'blur' } ],
  floor: [ { required: true, type: 'number', message: '请输入楼层', trigger: 'blur' } ],
  capacity: [ { required: true, type: 'number', message: '请输入容量', trigger: 'blur' } ],
  classroomType: [ { required: true, message: '请选择教室类型', trigger: 'change' } ],
  status: [ { required: true, message: '请选择状态', trigger: 'change' } ]
}

// 获取教室列表
async function fetchData() {
  loading.value = true
  try {
    const params: any = {
      ...searchForm,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === undefined) delete params[key]
    })
    const res = await axios.get('/api/classroom/list', { params })
    console.log('分页请求参数:', params)
    console.log('分页接口返回:', res.data)
    tableData.value = res.data?.data?.list || []
    total.value = res.data?.data?.total || 0
  } catch (e) {
    ElMessage.error('获取教室列表失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
function resetSearch() {
  searchForm.classroomCode = ''
  searchForm.classroomType = ''
  searchForm.capacity = undefined
  searchForm.status = ''
  pageNum.value = 1
  fetchData()
}

function onPageChange(val: number) {
  pageNum.value = val
  fetchData()
}

// 新增教室
function openAddDialog() {
  dialogMode.value = 'add'
  Object.assign(dialogForm, {
    classroomCode: '',
    campus: '',
    building: '',
    floor: 1,
    capacity: 1,
    classroomType: '',
    equipmentList: [],
    status: 'AVAILABLE'
  })
  dialogVisible.value = true
}

// 编辑教室
function openEditDialog(row: any) {
  dialogMode.value = 'edit'
  Object.assign(dialogForm, { ...row })
  dialogVisible.value = true
}

// 弹窗提交
function handleDialogSubmit() {
  dialogFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    try {
      if (dialogMode.value === 'add') {
        await axios.post('/api/classroom/add', {
          ...dialogForm,
          equipmentList: dialogForm.equipmentList || []
        })
        ElMessage.success('新增成功')
      } else {
        await axios.put(`/api/classroom/${dialogForm.classroomId}`, {
          ...dialogForm,
          equipmentList: dialogForm.equipmentList || []
        })
        ElMessage.success('修改成功')
      }
      dialogVisible.value = false
      fetchData()
    } catch (e) {
      ElMessage.error(dialogMode.value === 'add' ? '新增失败' : '修改失败')
    }
  })
}

// 删除教室
async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm(`确定要删除教室【${row.classroomCode}】吗？`, '提示', { type: 'warning' })
    await axios.delete(`/api/classroom/${row.classroomId}`)
    ElMessage.success('删除成功')
    fetchData()
  } catch (e) {
    // 用户取消或失败
  }
}

// 弹窗关闭重置
function resetDialog() {
  if (dialogFormRef.value) dialogFormRef.value.resetFields()
}

// 状态Tag类型
function statusTagType(status: string) {
  if (status === 'AVAILABLE') return 'success'
  if (status === 'MAINTENANCE') return 'warning'
  if (status === 'DISABLED') return 'info'
  return ''
}

onMounted(() => {
  fetchData()
})
</script> 

<style scoped>
.classroom-resource-wrapper {
  padding: 32px;
}
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.title {
  font-size: 22px;
  font-weight: bold;
}
.search-bar {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}
.pagination-bar {
  margin-top: 16px;
  display: flex;
  justify-content: flex-start;
}
</style> 